package com.hmdp.utils;

import cn.hutool.core.lang.func.Func;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;
@Component
public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    //带有过期时间的set
    public void set(String key,Object value,Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }


    public void setWithLogicalExpire(String key,Object value,Long time, TimeUnit unit){

        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R,ID> R getWithPassThrough(String keyPrefix, ID id, Class<R> type,
                                       Function<ID,R> dbFallback,Long time, TimeUnit unit){

        String key = keyPrefix+id;

        String json = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json,type);
        }

        if(json!=null){
            return null;
        }
        //redis中没有缓存
        R r = dbFallback.apply(id);
        if(r==null){
            stringRedisTemplate.opsForValue().set(key,"",time,unit);
            return null;
        }

        this.set(key,r,time,unit);


        return r;
    }



    public <R,ID> R getWithLogicalExpire(String keyPrefix, ID id, Class<R> type,
                                     Function<ID,R> dbFallback,Long time,TimeUnit unit){/// 逻辑过期解决缓存穿透

        String redisDataJSON = stringRedisTemplate.opsForValue().get(keyPrefix + id.toString());
        if(redisDataJSON==null){
            return null;
        }

        RedisData redisData = JSONUtil.toBean(redisDataJSON, RedisData.class);
        R r = JSONUtil.toBean((JSONObject)redisData.getData(),type);

        if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
            //如果没过期
            return r;
        }

        boolean isLocked = tryLock("lock:shop:"+id);
        if(isLocked){

            try {
                executorService.submit(()-> this.setWithLogicalExpire(keyPrefix+id,dbFallback.apply(id),
                        time,unit
                ));
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unlock("lock:shop:"+id);
            }
        }
        return r;

    }

    private boolean tryLock(String lock){
        Boolean locked = stringRedisTemplate.opsForValue().setIfAbsent(lock, "locked", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(locked);
    }

    private void unlock(String lock){
        stringRedisTemplate.delete(lock);
    }



}
